package com.pearadmin.pro.modules.weixin.service.impl;

import com.pearadmin.pro.modules.weixin.service.WeiChatCallbackService;
import com.pearadmin.pro.modules.weixin.util.AesException;
import com.pearadmin.pro.modules.weixin.util.MessageUtil;
import com.pearadmin.pro.modules.weixin.util.WXBizMsgCrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Map;

@Service
@Slf4j
public class WeiChatCallbackServiceImpl implements WeiChatCallbackService {
    //企业微信id
    @Value("${weixin.corpId}")
    private String corpId ;

    @Value("${weixin.sToken}")
    private String sToken ;

    @Value("${weixin.sEncodingAESKey}")
    private String sEncodingAESKey;

    private WXBizMsgCrypt getWXBizMsgCrypt() throws AesException {
        return new WXBizMsgCrypt(sToken, sEncodingAESKey, corpId);
    }


    @Override
    public String verifyURL(String msg_signature, String timestamp, String nonce, String echostr) {
        try {
            WXBizMsgCrypt wxcpt = getWXBizMsgCrypt();
            String sEchoStr; //需要返回的明文
            sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp,
                    nonce, echostr);
            return sEchoStr;
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return "无";
    }

    @Override
    public String doCallBack(HttpServletRequest request, String msgSignature, String timeStamp, String nonce) {
        try {
            InputStream inputStream = request.getInputStream();
            String postData = IOUtils.toString(inputStream, "UTF-8");
            WXBizMsgCrypt wxcpt = getWXBizMsgCrypt();
            //解密
            String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, postData);
            //将post数据转换为map
            Map<String,Object> dataMap = MessageUtil.parseXml(sMsg);
            String msgType = dataMap.get("MsgType").toString();
            if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)){
                String eventType = dataMap.get("Event").toString();
                log.info("审批回调通知，Event:"+eventType);
                if(eventType.equals("sys_approval_change")){
                    approvalBusiness(dataMap);
                }
            }
            //将post数据转换为map
//            Map<String, Object> dataMap = MessageUtil.xml2map(sMsg);
//            log.info("通知消息:{}" , dataMap);
            //然后去操作你的业务逻辑
        } catch (Exception e) {
            e.printStackTrace();
            log.info("企业微信接收回调消息失败" );
        }
        return "success";
    }

    /**
     * 审批业务
     * @param dataMap
     * @return
     */
    public void  approvalBusiness(Map<String,Object> dataMap){
        if(ObjectUtils.isEmpty(dataMap.get("ApprovalInfo"))){
            return ;
        }
        Map<String,Object> dataMapddsdfsa = (Map<String, Object>) dataMap.get("ApprovalInfo");
        log.info("审批模板Id{}",dataMapddsdfsa.get("TemplateId"));
        log.info("审批状态{}",dataMapddsdfsa.get("SpStatus")); // 1-审批中；2-已通过；3-已驳回；4-已取消
        log.info("审批单号{}",dataMapddsdfsa.get("SpNo")); // 审批单号

    }


}
